package com.zhz.order.controller;

import com.zhz.annocation.Idempotent;
import com.zhz.order.pojo.Order;
import com.zhz.order.service.OrderService;
import com.zhz.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private IdWorker idWorker;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @GetMapping("/genToken")
    public String genToken() {
        String token = String.valueOf(idWorker.nextId());
        redisTemplate.opsForValue().set(token, 0, 30, TimeUnit.MINUTES);
        return token;
    }
    
    /**
     * 生成订单
     *
     * @param order
     * @return
     */
    @Idempotent
    @PostMapping("/addOrder2")
    String addOrder2(@RequestBody Order order, HttpServletRequest request) {
        //令牌删除成功,代表不是重复请求,执行具体业务
        order.setId(String.valueOf(idWorker.nextId()));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        int result = orderService.addOrder(order);
        if (result == 1) {
            System.out.println("success");
            return "success";
        } else {
            System.out.println("fail");
            return "fail";
        }
    }
    
    /**
     * 生成订单
     *
     * @param order
     * @return
     */
    @PostMapping("/addOrder")
    String addOrder(@RequestBody Order order, HttpServletRequest request) {
        
        //获取令牌
        String token = request.getHeader("token");
        
        //校验令牌
        try {
            if (redisTemplate.delete(token)) {
                //令牌删除成功,代表不是重复请求,执行具体业务
                order.setId(String.valueOf(idWorker.nextId()));
                order.setCreateTime(new Date());
                order.setUpdateTime(new Date());
                int result = orderService.addOrder(order);
                if (result == 1) {
                    System.out.println("success");
                    return "success";
                } else {
                    System.out.println("fail");
                    return "fail";
                }
            } else {
                //删除令牌识别,重复请求
                System.out.println("repeat request");
                return "repeat request";
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常,请重试");
        } finally {
            
        }
    }
}
